<template>
    <!--    <div title="编辑规则" :visible.sync="addSopVisible" width="40%" @click="close">-->
    <div>
        <!-- 新建规则 -->
        <el-button plain @click="back">返回</el-button>
        <el-form ref="form" :model="saveForm" style="padding: 0px 20px;" label-width="120px">
            <h3>基本信息</h3>
            <el-form-item label="规则名称：">
                <el-input v-model="saveForm.sopName" placeholder="请输入规则名称" style="width: 300px;"></el-input>
            </el-form-item>
            <br/>
            <el-form-item label="规则描述：">
                <el-input
                    type="textarea"
                    :rows="3"
                    placeholder="请输入规则描述"
                    v-model="saveForm.sopDescription" style="width: 300px;">
                </el-input>
            </el-form-item>
            <br>
            <el-form-item label="选择群聊：" style="width: 500px;">
                <el-button icon="el-icon-plus" style="border:1px solid #409eff; color: #409eff;"
                           @click="addClientGroup('add')">默认按钮
                </el-button>
                <el-tag v-for="tag in saveForm.members" :key="tag.clientGroupName" closable @close="closeTagHandle(tag)"
                        style="margin-right: 10px"> {{ tag.clientGroupName }}
                </el-tag>
                已选择{{saveForm.members.length}}个群聊
            </el-form-item>
        </el-form>
        <el-form :inline="true" :model="sopForm" style="padding: 0px 30px;">
            <h3>设置触发条件</h3>
            <el-form-item label="设置规则：">
                <el-button icon="el-icon-plus" style="border:1px solid #409eff; color: #409eff;"
                           @click="openContentHandle">
                    添加规则
                </el-button>
            </el-form-item>
            <br>
            <el-form-item v-for="(item, index) in pushContentList" :key="index">
                <div style="display:flex;justify-content: space-between">
                    <div><i class="el-icon-s-management"></i>{{ item.alertMessage }}</div>
                    <div>
                        <el-button type="text" icon="el-icon-edit"
                                   @click="editContentHandle(item, index)"></el-button>
                        <el-button type="text" icon="el-icon-delete"
                                   @click="pushContentList.splice(pushContentList.indexOf(index), 1)"></el-button>
                    </div>
                </div>
                <div v-if="item.radio == '1'">添加规则后，{{ item.sopTime1 }} 小时 {{ item.sopTime2
                    }}
                    分钟后提醒发送（{{ item.alertMessage }}）
                </div>
                <div v-if="item.radio == '2'">添加规则后，{{ item.sopTime3 }} 天 {{ item.sopTime4 }}
                    后提醒发送（{{ item.alertMessage }}）
                </div>
                <div style="border-radius: 5px; padding: 10px;background-color: #f1f5f7">
                    <div style="border-radius: 5px; padding: 5px;margin-bottom: 10px;background-color: #FFFFFF"
                         v-for="(item1, index1) in item.contentList" :key="index1">
                        <img v-if="item1.imageUrl" :src="item1.imageUrl" class="avatar">
                        <div v-else>{{ item1.content }}</div>
                    </div>
                    <div>共{{ item.contentList.length }}条</div>
                </div>
            </el-form-item>
        </el-form>
        <div slot="footer" class="dialog-footer">
            <el-button size="small" type="primary" @click="submitHandle">确定</el-button>
        </div>

        <!-- 添加群聊 -->
        <el-dialog title="添加群聊" :visible.sync="addClientGroupVisible" width="37%" @click="close" style="padding: 10px 20px;">
            <div style="padding: 0px 0px 0px 30px;">
                <div style="color:#5160ff">
                    注意：如果客群已经设置sop成员入群规则，默认覆盖！
                </div>
                <MultipleSelect ref="selectMultipleMember" :listFields="listFields" :dataSource="transferData"
                                type="filter"/>
                <div class="button-center" style="padding: 10px 10px;">
                    <el-button size="mini" @click="close">取消</el-button>
                    <el-button size="mini" type="primary" @click="getGroupHandle('addGroup')">确定</el-button>
                </div>
            </div>
        </el-dialog>

        <el-dialog :title="submitType == 'add' ? '添加规则' : '修改规则'" :visible.sync="addSopVisible" width="40%"
                   @click="close">
            <el-form :inline="true" :model="saveTaskForm" class="user-search" style="margin-left: 40px;">
                <el-form-item>
                    <el-radio v-model="saveTaskForm.radio" label="1">
                        加入规则后
                        <el-input type="number" v-model="saveTaskForm.sopTime1" :disabled="saveTaskForm.radio != '1'"
                                  style="width: 120px;height: 25px;" size="small"></el-input>
                        小时
                        <el-input type="number" v-model="saveTaskForm.sopTime2" :disabled="saveTaskForm.radio != '1'"
                                  style="width: 120px;height: 25px;" size="small"></el-input>
                        分钟

                        <el-radio v-if="saveTaskForm.radio == 1" v-model="radio1" label="1" :disabled="saveTaskForm.radio != '1'">
                            提醒 + 内容发送
                        </el-radio>
                        <el-radio v-if="saveTaskForm.radio == 1" v-model="radio1" label="2" :disabled="saveTaskForm.radio != '1'">
                            仅提醒
                        </el-radio>
                    </el-radio>
                </el-form-item>
                <br>
                <el-form-item>
                    <el-radio v-model="saveTaskForm.radio" label="2">
                        加入规则后
                        <el-input type="number" v-model="saveTaskForm.sopTime3" :disabled="saveTaskForm.radio != '2'"
                                  style="width: 120px;"  size="small"></el-input>
                        天
                        <el-time-select v-model="saveTaskForm.sopTime4" :disabled="saveTaskForm.radio != '2'" size="small" style="width:25%;"
                                        :picker-options="{
                        start: '08:30',
                        step: '00:15',
                        end: '17:30'
                      }"
                                        placeholder="时间">
                        </el-time-select>
                        <el-radio v-if="saveTaskForm.radio == '2'" v-model="radio2" label="1" :disabled="saveTaskForm.radio != '2'">
                            提醒 + 内容发送
                        </el-radio>
                        <el-radio v-if="saveTaskForm.radio == '2'" v-model="radio2" label="2" :disabled="saveTaskForm.radio != '2'">
                            仅提醒
                        </el-radio>
                    </el-radio>
                </el-form-item>
                <br>
                <el-form-item>
                    <div style="width: 550px">
                        <el-card>
                            <div slot="header" style="padding: 0px 20px;">
                                <div style="font-size: 14px; padding:0px;">提醒内容：</div>
                            </div>
                            <div style="padding: 0px;">
                                <el-input v-model="saveTaskForm.alertMessage"
                                          type="textarea" placeholder="请输入任务内容"></el-input>
                            </div>
                        </el-card>
                    </div>
                </el-form-item>
                <br>
                <div v-if="radio1 == 1 || radio2 == 1" style="padding-left: -20px">
                    <TypeContentText ref="contentText" style="width: 550px;margin:0px;" :contentList="contentList" type="sop" />
                </div>
            </el-form>
            <div slot="footer" class="dialog-footer">
                <el-button size="small" @click="close">取消</el-button>
                <el-button size="small" type="primary" @click="submitContentHandle()">确定</el-button>
            </div>
        </el-dialog>
    </div>
</template>

<script>

    import MultipleSelect from "@/components/list_multiple_select/list_multiple_select"
    import TypeContentText from "@/components/type_content_text/type_content_text"
    import MaterialContentText from "@/components/material_content_text/material_content_text"

    const saveTaskForm = {
        alertMessage: '',
        sendTimeType: '1',
        sopTime1: '',
        sopTime2: '',
        sopTime3: '',
        sopTime4: '',
        radio: '1',
        radio1: '1',
        radio2: '1'
    }

    const initContentList = [{
        contentType: 1,
        content: '',
        imageUrl: '',
        linkContent: {
            linkAddress: '',
            linkTitle: '',
            content: ''
        }
    }]
    export default {
        name: "sop",
        props: {
            sopData: {
                type: Object,
                default: () => {
                }
            },
            creatType: {
                type: String,
                default: ""
            },
        },
        data() {
            return {
                radio: '1',
                radio1: '1',
                radio2: '1',
                taskForm: {},
                addSopVisible: false,
                saveForm: {
                    sopName: '',
                    sopDescription: '',
                    members: [],
                },
                addClientGroupVisible: false,

                listFields: {
                    clientGroupName: '群聊名称',
                    empName: '群主名称',
                },
                transferData: [],
                sopForm: {},
                submitType: '',
                editIndex: 0,
                saveTaskForm: {...saveTaskForm},
                pushContent: {},
                contentList: [...initContentList],
                pushContentList: []
            }
        },
        // 注册组件
        components: {
            MultipleSelect, TypeContentText,MaterialContentText
        },

        watch: {
            sopData(n, o) {
                this.saveForm['sopName'] = n.sopName
                this.saveForm['members'] = n.groupList

                let pushMessage = JSON.parse(n.pushMessage)
                let messageList = []

                pushMessage.map((item) => {
                    let data = {}
                    let contentList = []

                    data['alertMessage'] = item.alertMessage
                    data['radio'] = item.radio

                    let alertTime = formatDuring(item.alertTime)

                    if (item.radio == '1') {
                        data['sendTimeField1'] = (alertTime.days * 24) + alertTime.hours
                        data['sendTimeField2'] = alertTime.minutes
                    } else if (item.radio == '2') {
                        data['sendTimeField3'] = alertTime.days
                        data['sendTimeField4'] = (alertTime.hours.toString().length == 1 ? 0 + alertTime.hours.toString() : alertTime.hours) + ":" + (alertTime.minutes.toString().length == 1 ? 0 + alertTime.minutes.toString() : alertTime.minutes) + ":" + (alertTime.seconds.toString().length == 1 ? 0 + alertTime.seconds.toString() : alertTime.seconds)
                    }

                    item.pushMessage.map((item1) => {
                        if (item1.pushType == 1) {
                            contentList.push({
                                contentType: 1,
                                content: item1.pushMessage,
                                imageUrl: '',
                                linkContent: {
                                    linkAddress: '',
                                    linkTitle: '',
                                    content: ''
                                }
                            })
                        } else if (item1.pushType == 2 || item1.pushMessage == 3) {
                            contentList.push({
                                contentType: item1.pushType,
                                content: "",
                                imageUrl: item1.pushMessage,
                                linkContent: {
                                    linkAddress: '',
                                    linkTitle: '',
                                    content: ''
                                }
                            })
                        }
                    })

                    data['contentList'] = contentList

                    messageList.push(data)
                })

                this.pushContentList = messageList
            }
        },

        mounted() {
            this.$request("/api/custGroup/selectGroup/1_0", "", "POST").then((data) => {
                this.transferData = [...data.rows]
            })
        },
        methods: {

            currentHandle(data) {
                this.currentPanel = data;
            },

            saveMission() {
                this.saveTaskForm.messageType = '1'

                this.emit("addRuleHandle", this.saveTaskForm);
            },
            handleRemove(file) {

            },
            // 新建群聊
            addClientGroup() {
                this.addClientGroupVisible = true;
            },
            close() {
                this.addSopVisible = false;
                this.addClientGroupVisible = false;
            },
            closeTagHandle(tag) {
                this.saveForm.members.splice(this.saveForm.members.indexOf(tag), 1);
            },

            getGroupHandle(message) {
                let data = this.$refs.selectMultipleMember.getData();
                this.saveForm.members = data
                this.addClientGroupVisible = false
            },
            openContentHandle() {
                this.saveTaskForm = {...saveTaskForm}
                this.contentList = [...initContentList]
                this.submitType = 'add'
                this.addSopVisible = true
            },
            editContentHandle(data, index) {
                this.saveTaskForm = {...data};
                this.editIndex = index;
                this.submitType = 'edit';
                this.addSopVisible = true;
                let json = JSON.stringify(data.contentList)
                this.$nextTick(() => {
                    this.contentList = JSON.parse(json)
                })
            },
            submitContentHandle() {
                let pushContent = {...this.saveTaskForm}
                pushContent['contentList'] = this.$refs.contentText.getData()
                if (this.submitType == 'add') {
                    this.pushContentList.push(pushContent)
                } else {
                    this.pushContentList[this.editIndex] = pushContent
                }

                this.$refs.contentText.initData()
                this.addSopVisible = false
            },
            submitHandle() {
                let me = this

                let form = {...me.saveForm}

                if (form['members'] == null || form['members'].length == 0) {
                    me.$message.error("未选择群聊")
                    return
                }

                let pushContentList = [...me.pushContentList]

                let pushMessageList = []

                pushContentList.map((item) => {
                    let alertTime = 0;

                    if (item.radio == '1') {
                        alertTime = (item.sopTime1 * 60 * 60 * 1000) + (item.sopTime2 * 60 * 1000)
                    } else if (item.radio == '2') {
                        let time = 0;
                        if (typeof (item.sopTime4) == "string") {
                            time = me.$moment(me.$moment().format("YYYY-MM-DD") + " " + item.sopT4).unix() * 1000
                        } else {
                            time = me.$moment(item.sopTime4).valueOf()
                        }
                        alertTime = (item.sopTime3 * 24 * 60 * 60 * 1000) + (time - parseInt(me.$moment().startOf('day').format('x')))
                    } else {
                        me.$message.error("未选择提醒时间")
                        return
                    }

                    let pushMessage = []

                    item.contentList.map((item1) => {
                        pushMessage.push({
                            pushType: item1.contentType,
                            pushMessage: item1.imageUrl != null && item1.imageUrl != "" ? item1.imageUrl : item1.content
                        })
                    })

                    pushMessageList.push({
                        alertTime,
                        radio: item.radio,
                        alertMessage: item.alertMessage,
                        pushMessage
                    })
                })

                let empArr = []

                form['members'].map((data) => {
                    empArr.push(data.clientGroupId)
                })

                form['relationId'] = empArr.toString()
                form['creator'] = "管理员"
                form['sopType'] = "2"
                form['pushMessage'] = JSON.stringify(pushMessageList)

                delete form['members']

                let url = "/api/sop/addSop/1_0"
                if (this.creatType == 'edit') {
                    url = "/api/sop/updateSop/1_0"
                    form['sopId'] = me.sopData.sopId
                }

                me.$request(url, form, "POST").then((data) => {
                    if (this.creatType == 'edit') {
                        me.$message.success("修改成功")
                    } else {
                        me.$message.success("添加成功")
                    }
                    me.back()
                })
            },
            back() {
                this.$emit("currentHandler", "list")
            },
        }
    }
</script>

<style scoped>

</style>
